package com.hmdp.inteceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOGIN_USER_TTL;
@Component
public class TokenRefreshInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate redis ;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求头中得到token
        String token = request.getHeader("authorization");
        if (StrUtil.isBlank(token)) {
            return true;
        }
        //2.从redis中获取用户
        Map<Object, Object> entries = redis.opsForHash().entries(RedisConstants.LOGIN_USER_KEY + token);
        //TODO MAP TO BEAN
        //3.判断用户是否存在
        if(entries.isEmpty()){
            return true;
        }
        //将查询到的hash数据转为UserDTO
        UserDTO user = BeanUtil.fillBeanWithMap(entries, new UserDTO(), false);
        //5.存在，保存到ThreadLocal中
        UserHolder.saveUser(user);
        // 更新有效期,不操作30分钟才过期
        redis.expire(RedisConstants.LOGIN_USER_KEY + token,LOGIN_USER_TTL, TimeUnit.MINUTES);
        //6.放行
        return true;
    }
}
